package com.cskaoyan.wordmemorize.service.impl;

import com.cskaoyan.wordmemorize.dto.app.AIReviewReadDTO;
import com.cskaoyan.wordmemorize.request.AIReviewReadCommand;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AIReadGenerator {

    @Value("classpath:/prompt/ai-read-system-message.st")
    Resource systemResource;

    @Value("classpath:/prompt/ai-read-user-message.st")
    Resource userResource;

    @Autowired
    ChatClient chatClient;

//    public AIReviewReadDTO generateReadContent(AIReviewReadCommand command) {
    public List<AIReviewReadDTO> generateReadContent(AIReviewReadCommand command) {
        // 创建系统提示词
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
        Message systemMessage = systemPromptTemplate.createMessage();

        // 创建用户提示词
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("situation", command.getSituationName());
        paramMap.put("option", command.getOptionName());
        paramMap.put("words", command.getVocList().toString());

        if ("教育模式".equals(command.getSituationName())) {
            paramMap.put("type", "短文");
        } else if ("对话模式".equals(command.getSituationName())) {
            paramMap.put("type", "对话");
        } else {
            paramMap.put("type", "故事");
        }

        PromptTemplate userPrompt = new PromptTemplate(userResource, paramMap);
        Message userMessage = userPrompt.createMessage();

        // 构造完整提示词并调用AI
        Prompt prompt = new Prompt(List.of(systemMessage, userMessage));


        List<AIReviewReadDTO> result = chatClient
                // 设置prompt
                .prompt(prompt)
                // 发起请求
                .call()
                // 获取
                .entity(new ParameterizedTypeReference<List<AIReviewReadDTO>>() {
                });


        return result;
    }
}
